package top.i51213.fastaction;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import top.i51213.fastaction.action.share.ShareActonComponent;
import top.i51213.fastaction.action.image.ImageCompressor;
import top.i51213.fastaction.action.pdf.ToPdfActonComponent;
import top.i51213.fastaction.action.print.PrintActionComponent;
import top.i51213.fastaction.action.SameLast;
import top.i51213.fastaction.action.save.SaveActionComponent;
import top.i51213.fastaction.action.zip.ZipCompressActonComponent;
import top.i51213.fastaction.action.Action;
import top.i51213.fastaction.action.BaseActonComponent;
import top.i51213.fastaction.action.Data;
import top.i51213.fastaction.action.DataType;
import top.i51213.fastaction.action.FirstActionComponent;
import top.i51213.fastaction.action.image.ImageCompressActonComponent;

public class ReceiveActivity extends AppCompatActivity {
    private static final String PrivateAction="top.i51213.fastaction.action.Receive";
    public static final String TAG = ReceiveActivity.class.getSimpleName();
    ActionActiveAdapter adapter;
    FirstActionComponent firstActionManger;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receive);
        showActionComponents();
        initActionActive();
        textView = findViewById(R.id.receive_title);
        Log.d(TAG, getRunningActivityName(this));
        Log.d(TAG, getIntent().getComponent().getClassName());
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();
         if (type != null) {
            DataType dataType = null;
            if (type.startsWith("image/")) {
                dataType = DataType.IMAGE;
            } else if ("application/pdf".equalsIgnoreCase(type)) {
                dataType = DataType.PdfFile;
            }
            else if ("*/*".equalsIgnoreCase(type)) {
                dataType = DataType.Any;
            }
            if (dataType != null) {
                if(PrivateAction.equals(action)){
                    ArrayList<Uri> list = new ArrayList<>(Collections.singletonList(intent.getData()));
                    dealList(list, dataType);
                }else if (Intent.ACTION_SEND.equals(action)) {
                    dealStream(intent, dataType);
                } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
                    dealMultipleStream(intent, dataType);
                }
            } else {
                Toast.makeText(this, "不支持的数据类型", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void showActionComponents() {
        ListView listView = findViewById(R.id.lv_action_component);
        String[] itemData = {"图片压缩", "图片压缩(高清)", "图片压缩(超高清)", "Zip打包", "转Pdf", "打印", "分享", "保存"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.simple_list_item_1, itemData);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            switch (position) {
                case 0:
                    this.adapter.addActionData(new ImageCompressActonComponent(this, ImageCompressor.LimitRectSize.PX400));
                    break;
                case 1:
                    this.adapter.addActionData(new ImageCompressActonComponent(this, ImageCompressor.LimitRectSize.PX800));
                    break;
                case 2:
                    this.adapter.addActionData(new ImageCompressActonComponent(this, ImageCompressor.LimitRectSize.PX1200));
                    break;
                case 3:
                    this.adapter.addActionData(new ZipCompressActonComponent(this));
                    break;
                case 4:
                    this.adapter.addActionData(new ToPdfActonComponent(this));
                    break;
                case 5:
                    this.adapter.addActionData(new PrintActionComponent(this));
                    break;
                case 6:
                    this.adapter.addActionData(new ShareActonComponent(this));
                    break;
                case 7:
                    this.adapter.addActionData(new SaveActionComponent(this));
                    break;
            }
        });
    }

    private void initActionActive() {
        RecyclerView recyclerView = findViewById(R.id.rv_action_active);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        ArrayList<Action> actionList = new ArrayList<>();
        adapter = new ActionActiveAdapter(actionList);
        recyclerView.setAdapter(adapter);
        ItemTouchHelper helper = new ItemTouchHelper(new MyItemTouchCallback(adapter));
        helper.attachToRecyclerView(recyclerView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_receive, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_action_receive_start) {
            start();
        }
        return true;
    }

    private void start() {
        if (firstActionManger == null) {
            Toast.makeText(this, "无任何数据待处理!", Toast.LENGTH_SHORT).show();
            return;
        }
        List<Action> myActions = adapter.getActionList();
        BaseActonComponent last = firstActionManger;
        for (Action action : myActions) {
            BaseActonComponent thisAction = (BaseActonComponent) action;
            if (!last.checkNext(thisAction)) {
                Toast.makeText(this, thisAction.getTitle() + "无法匹配上一命令，请修改!", Toast.LENGTH_LONG).show();
                return;
            }
            if (!(thisAction instanceof SameLast)) {
                last = thisAction;
            }
        }
        last = firstActionManger;
        for (Action action : myActions) {
            BaseActonComponent thisAction = (BaseActonComponent) action;
            last.feedNext(thisAction);
            if (!(thisAction instanceof SameLast)) {
                last = thisAction;
            }
        }
        Data result = last.getOutputData();
        List<Uri> uris = result.getUris();
        //System.out.println("最终输出:" + uris);
        Toast.makeText(this, "已完成", Toast.LENGTH_SHORT).show();
        //finish();
    }

    private static String getRunningActivityName(Context context) {
        String contextString = context.toString();
        return contextString.substring(contextString.lastIndexOf(".") + 1, contextString.indexOf("@"));
    }

    protected void dealStream(Intent intent, DataType dataType) {
        Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
        ArrayList<Uri> list = new ArrayList<>();
        list.add(uri);
        dealList(list, dataType);
    }

    protected void dealMultipleStream(Intent intent, DataType dataType) {
        ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
        dealList(list, dataType);
    }

    @SuppressLint("SetTextI18n")
    private void dealList(ArrayList<Uri> list, DataType dataType) {
        textView.setText("数据格式:" + dataType.toString() + "\n数量:" + list.size());
        Data data = new Data(dataType);
        data.addData(dataType, list);
        firstActionManger = new FirstActionComponent(this, data);
    }

    public static void startThis(Context context, @ReceiveClassName.ClassName String cls, ArrayList<Uri> uris, String mimeType) {
        if (uris.size() == 0) return;
        Intent intent = uris.size() > 1 ? new Intent(Intent.ACTION_SEND_MULTIPLE) : new Intent(Intent.ACTION_SEND);
        intent.setComponent(new ComponentName(context.getPackageName(), cls));
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setType(mimeType);
        if (uris.size() > 1) {
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
        } else {
            intent.putExtra(Intent.EXTRA_STREAM, uris.get(0));
        }
        if(!(context instanceof Activity)){
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void startThis(Context context, Uri data, String mimeType) {
        Intent intent =  new Intent(PrivateAction);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(data,mimeType);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        try {
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}